<template>
  <n-modal id="basic-modal" v-bind="getBindValue" v-model:show="showModal" :closable="!modalLoading" @close="closeModal"
           class="pt-0" :close-on-esc="!modalLoading" :mask-closable="!modalLoading">
    <template #header>
      <div class="w-full cursor-move pt-8" id="basic-modal-bar" v-show="getBindValue.title">{{ getBindValue.title }}</div>
    </template>
    <template #default>
      <slot name="default"></slot>
    </template>
    <template v-if="!$slots.action" #action>
      <n-space>
        <n-button :disabled="modalLoading" size="large" @click="closeModal">取消</n-button>
        <n-button :loading="modalLoading" size="large" type="primary" @click="handleSubmit">
          {{ positiveText }}
        </n-button>
      </n-space>
    </template>
    <template v-else #action>
      <slot name="action"></slot>
    </template>
  </n-modal>
</template>

<script setup>
import { getCurrentInstance, ref, unref, computed, useAttrs, nextTick } from 'vue'
import { basicProps } from './props'
import { deepMerge } from '@/utils'
import startDrag from '@/utils/drag'

const attrs = useAttrs()
const props = defineProps({ ...basicProps })
const emit = defineEmits(['close', 'confirm', 'register'])

const showModal = ref(false)
const modalLoading = ref(false)

const propsRef = ref(null)

const setProps = modalProps => {
  propsRef.value = deepMerge(unref(propsRef) || {}, modalProps)
}

const getProps = computed(() => {
  return { ...props, ...(unref(propsRef)) }
})

const getBindValue = computed(() => {
  return {
    ...attrs,
    ...unref(getProps),
    ...unref(propsRef),
  }
})

const positiveText = computed(() => {
  const { positiveText } = propsRef.value
  return positiveText || props.positiveText
})

const openModal = () => {
  showModal.value = true
  nextTick(() => {
    const oBox = document.getElementById('basic-modal')
    const oBar = document.getElementById('basic-modal-bar')
    startDrag(oBar, oBox)
  })
}

const setModalLoading = val => {
  modalLoading.value = val
}

const closeModal = () => {
  showModal.value = false
  setModalLoading(false)
  emit('close')
}

const handleSubmit = () => {
  emit('confirm')
}

const currentInstance = getCurrentInstance()
if (currentInstance) {
  emit('register', {
    setProps,
    openModal,
    closeModal,
    setModalLoading,
  })
}
</script>

<style lang="less" scoped>
#basic-modal {
}
</style>
